package com.diamond.web.security;

import java.util.List;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.diamond.web.model.system.Permission;
import com.diamond.web.model.system.Role;
import com.diamond.web.model.system.User;
import com.diamond.web.service.system.PermissionService;
import com.diamond.web.service.system.RoleService;
import com.diamond.web.service.system.UserService;
import com.diamond.web.utils.ApplicationInitUtils;

/**
 * 用户身份验证,授权 Realm 组件
 * 
 * @author Diamond
 * @since 2015年11月28日
 **/
@Component
public class SecurityRealm extends AuthorizingRealm {

	Logger log = Logger.getLogger(getClass());
	
    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionService permissionService;

    /**
     * 权限检查
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	log.info("Permission Checked");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = String.valueOf(principals.getPrimaryPrincipal());
        if(username.equals(ApplicationInitUtils.SuperAdmin)){
        	authorizationInfo.addRole(RoleSign.SUPER_ADMIN);
        	List<String> allPermissionsSign = permissionService.selectAllSign();
        	System.err.println("is super admin add all permission!!!");
        	for (String sign : allPermissionsSign) {
        		 authorizationInfo.addStringPermission(sign);
        		 System.err.println("add permission:"+sign);
			}
        	return authorizationInfo;
        }
        final User user = userService.selectByUsername(username);
        final List<Role> roleInfos = roleService.selectRolesByUserId(user.getId());
        for (Role role : roleInfos) {
        	if(role==null){
        		continue;
        	}
            // 添加角色
            System.err.println(role);
            authorizationInfo.addRole(role.getRoleSign());
            final List<Permission> permissions = permissionService.selectPermissionsByRoleId(role.getId());
            for (Permission permission : permissions) {
                // 添加权限
                System.err.println(permission);
                authorizationInfo.addStringPermission(permission.getPermissionSign());
                addParentPermission(permission,authorizationInfo);
            }
        }
        return authorizationInfo;
    }
    
    

    private void addParentPermission(Permission permission,
			SimpleAuthorizationInfo authorizationInfo) {
    	if(permission.getParent()!=null){
    		authorizationInfo.addStringPermission(permission.getParent().getPermissionSign());
    		addParentPermission(permission.getParent(), authorizationInfo);
    	}
	}



	/**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    	log.info("Login Checked");
        String username = String.valueOf(token.getPrincipal());
        String password = new String((char[]) token.getCredentials());
        //先通过配置文件验证是否是超级管理员用户
        if(ApplicationInitUtils.SuperAdmin.equals(username)&&ApplicationInitUtils.SuperPwd.equals(password)){
        	log.info("超级管理员登录！");
        }else{
        	// 通过数据库进行验证
            final User authentication = userService.authentication(new User(username, password));
            if (authentication == null) {
                throw new AuthenticationException("用户名或密码错误.");
            }
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
        return authenticationInfo;
    }

}
